const router = require("koa-router")();
const JWT = require("jsonwebtoken");

const userList = [
  {
    id: "1",
    username: "zhangsan",
    password: "zhangsan",
    nickname: "张三",
    avator: "https://robohash.org/1231",
    addressList: [
      {
        id: "1",
        nickname: "小三三",
        tel: "13111111111",
        address: "上海市奉贤区八维宏业校区",
      },
      {
        id: "2",
        nickname: "小三三",
        tel: "13111111111",
        address: "北京市海淀区八维上地校区",
      },
    ],
  },
  {
    id: "2",
    username: "lisi",
    password: "lisi",
    nickname: "李四",
    avator: "https://robohash.org/123112312311",
    addressList: [
      {
        id: "1",
        nickname: "李四",
        tel: "13456666666",
        address: "河北邯郸魏县",
      },
      {
        id: "2",
        nickname: "李四",
        tel: "13456666666",
        address: "河北邯郸永年",
      },
    ],
  },
];

router.post("/login", (ctx) => {
  const { username, password } = ctx.request.body;
  const item = userList.find(
    (v) => v.username === username && v.password === password
  );
  if (item) {
    ctx.body = {
      code: 200,
      message: "登录成功，欢迎" + item.nickname,
      data: {
        userInfo: item,
        token: JWT.sign(item, "345654321"),
      },
    };
  } else {
    ctx.body = {
      code: 400,
      message: "账号密码错误， 重新登录",
    };
  }
});

module.exports = router;
